#include "testrecvsend.h"

TestRecvSend::TestRecvSend()
{
    times=0;
}


QByteArray TestRecvSend::getType(QByteArray bytearray)
{
    QJsonParseError jsonError;
    QJsonDocument paserDoc = QJsonDocument::fromJson(bytearray,&jsonError);
    if (jsonError.error == QJsonParseError::NoError)
    {
        auto paserObj =paserDoc.object();
        if (paserObj.contains("type"))
        {
            return paserObj["type"].toString().toStdString().c_str();
        }
    }
    return "";
}

int TestRecvSend::getInfo( shared_ptr<SockClient> &client)
{
    //while (true)
    {
        int len=0;
        int ret=client->stableRecv((char*)&len,4);
        //cout<<"读取到的信息长度"<<len<<endl;
        if(ret>0)
        {
            char *mem=(char*)malloc(len+4);
            memset(mem,0,len+4);

            client->stableRecv(mem,len);
           // cout<<"读取到的信息为"<<mem<<" "<<endl;
            QString type=getType(mem);
           // cout<<"读取到的信息类型"<<type.toStdString().c_str()<<endl;
            free(mem);
            if(type=="First")
            {
                return 1;
            }
            else if(type=="Second")
            {
                return 2;
            }

            if(type=="SendChess")
            {
                return 3;
            }

        }
    }

    return -1;
}


void TestRecvSend::front_test(NetworkGame &game,shared_ptr<SockClient> &client)
{
    while (tag) {
        game.sendChess(1,1);
        getInfo(client);
        times+=2;
    }
}

void TestRecvSend::back_test(NetworkGame &game,shared_ptr<SockClient> &client)
{
    while (tag) {
        getInfo(client);
        game.sendChess(1,1);
        times+=2;
    }
}

void TestRecvSend::spy_times(int seconds)
{
    sleep(seconds);
    tag=false;
}

void TestRecvSend::task()
{
    auto client =
            shared_ptr<SockClient>(new SockClient("127.0.0.1",7777));
    if(client->connectToHost()==-1)
    {
        //超时  你可以在这里设置重传次数
        return;
    }


    //client->start();
    NetworkGame game;
    game.setNet(client);
    game.findTeam();
    if(getInfo(client)==1)
    {
        front_test(game,client);
    }
    else
    {
        back_test(game,client);
    }
}

void TestRecvSend::test()
{

    std::thread th[800];


    for(int i=0;i<800;i++)
    {
        th[i]=std::move(std::thread(&TestRecvSend::task,this));
    }
    //h[0]=std::move(std::thread(&TestRecvSend::spy_times,this,10));
    for(auto i=0;i<800;i++)
    {
        th[i].detach();
    }

    sleep(3600);
    cout<<"交互次数"<<times/(double)3600<<endl;
}
